$(document).ready(function(){
    var eContentNav = $('#contentNav'), eContent = $('#content'), eSubmitSec = $('#submitSec'), eShadeSec = $('#shadeSec'), ePreviewBtn = $('#previewBtn');
    var ansEvery = 10, ansNum = 7;
    eContent.focus(function(){
        if(eContentNav.hasClass('hide')){
            eSubmitSec.removeClass('hide');
            eContentNav.removeClass('hide');
            eContent.css('height',227);
        }
        if(uid == 0){
            eShadeSec.css({'height' : eContent.height() + 36, 'marginTop' : 0});
            eShadeSec.html('<span class="no-auth">如果您想回复，请您先 <a href="//wooo.wang/login.html">登录 · 注册</a> .</span>').addClass('md-preview-show');
            eContentNav.addClass('hide');
        }else{
            $(this).next('p').text('');
        }
    });
    var eSelectBtn = $('#selectBtn'), eSelectSec = $('#selectSec'), eSelectVal = $('#selectVal');
    eSelectBtn.on('click', function(){
        if(eSelectSec.hasClass('hide')) eSelectSec.removeClass('hide');
        else eSelectSec.addClass('hide');
    });
    eSelectSec.on('click', 'li', function(){
        eSelectBtn.text($(this).text());
        eSelectVal.val($(this).attr('val'));
        eSelectSec.addClass('hide');
    });
    // textarea框自动增高功能
    eContent.on('propertychange input', function(){
        var height = $(this)[0].scrollHeight;
        if(height >= 227){
            $(this).css('height', height);
        }
    });
    // 上传图片功能
    var key='';
    var uploader = Qiniu.uploader({
        runtimes: 'html5,html4',    //上传模式,依次退化
        browse_button: 'imgBtn',       //上传选择的点选按钮，**必需**
        uptoken : token,
        domain: 'http://img.wooo.wang/',
        //bucket 域名，下载资源时用到，**必需**
        //container: 'img',           //上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: '4mb',           //最大文件体积限制
        flash_swf_url: '',  //引入flash,相对路径
        max_retries: 3,                   //上传失败最大重试次数
        dragdrop: false,                   //开启可拖曳上传
        drop_element: '',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '4mb',                //分块上传时，每片的体积
        auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
        resize: {
            quality: 60,
            preserve_headers: false
        },
        init: {
            'FilesAdded': function(up, files) {
                plupload.each(files, function(file) {
                    eContent.val(eContent.val()+'\n![](http://img.wooo.wang/'+key+')\n').focus();
                });
            },
            'BeforeUpload': function(up, file) {
                // 每个文件上传前,处理相关的事情
            },
            'UploadProgress': function(up, file) {

            },
            'FileUploaded': function(up, file, info) {

            },
            'Error': function(up, err, errTip) {
                //上传出错时,处理相关的事情
            },
            'UploadComplete': function() {
                //队列文件处理完毕后,处理相关的事情
            },
            'Key': function(up, file) {
                // 该配置必须要在 unique_names: false , save_key: false 时才生效
                key = 'bbs/'+uid+'_'+oid+'_'+tid+'_'+new Date().getTime()+'.png';
                return key;
            }
        }
    });
    // 显示隐藏输入markdown对应的文本
    ePreviewBtn.on('click', function(){
        if(eShadeSec.hasClass('md-preview-show')){
            eShadeSec.removeClass('md-preview-show');
        }else{
            eShadeSec.css('height', eContent.height());
            eShadeSec.html(marked(eContent.val())).addClass('md-preview-show');
        }
    });
    $('#submitBtn').click(function(e){
        e.preventDefault();
        if($(this).hasClass('no-save')){
            return;
        }
        if(uid != 0){
            if(eContent.val() == ''){
                eContent.next('p').text('请书写一定的内容！');
            }else{
                $('#htmlContent').val(marked(eContent.val()));
                $('#form').submit();
            }
        }
    });
    // 回复帖子相关功能
    var eAnsSec = $('#ansSec');
    $('.replenishQ').on('click', function(){
       $('.edit-q').toggleClass('hide');
    });
    $('#patchBtn').on('click', function(e){
        e.preventDefault();
        $('#patchHtml').val(marked($('#patchMd').val()));
        $('#patchForm').submit();
    });
    eAnsSec.on('click', '.reply', function(){
       var that = this;
       var eP = $(that).parent('p');
       var editDiv = eP.next('.add-div');
       var type = $(that).data('type');
       var ansId = eP.data('aid');
       var eLi = $('#ans'+ansId);
       if(editDiv.length){
            eP.find('.red').removeClass('red');
            if(editDiv.hasClass('hide')){
                editDiv.removeClass('hide');
                $(that).addClass('red');
            }else{
                editDiv.addClass('hide');
                $(that).removeClass('red');
            }
            editDiv.find('.publish').data('type', type);
       }else{
           var str = '<div class="add-div"><div class="reply-content" id="replyContent'+ansId+'"></div><div id="ansPage'+ansId+'"></div>';
           if(uid){
               str += '<div class="editDiv"><p class="tip-msg"></p><textarea spellcheck="false" '+
               'placeholder="书写(支持markdown)..."></textarea><a href="javascript:void(0)" '+
               'class="publish" data-type="'+type+'">发布</a></div>';
           }else{
               str += '<p class="tip-msg">请 <a href="//wooo.wang/login.html" name="target">登录</a> '+
               '后再评论</p>';
           }
           str += '</div>';
           eP.after(str);
           $(that).addClass('red');
           if(eLi.data('reply') != 0){
               $.get("/tie/ajaxgetreply/tid/"+tid+"/aid/"+ansId, {}, function(res){
                   var data = $.parseJSON(res);
                   var str1 = '';
                   var replyContent = $('#replyContent'+ansId);
                   if(data.code == 200 && data.data.count > 0){
                       for(var i in data.data.list){
                           var tmpData = data.data.list[i];
                           str1 += '<div class="wooo">'+tmpData['html']+'</div><p class="faq-msg" data-aid="'+tmpData['id']+'">'+
                               '<a href="/u/'+tmpData['uid']+'.html" data-uid="'+tmpData['uid']+'">'+tmpData['nick']+'</a>&nbsp;&nbsp;'+
                               getReplyTime(tmpData['create'])+'.&nbsp;&nbsp;'+
                               '<a href="javascript:void(0)" class="replyBtn">回复</a>';
                           str1 += manager ? '&nbsp;&nbsp;<a href="javascript:void(0)" class="delAnsBtn">删除</a>' : '';
                           str1 += '</p>';
                       }
                       $('#ansPage'+ansId).html(page(ansId, data.data.count, ansEvery, 1, ansNum));
                   }else{
                       str1 += '<div class="wooo"><p>获取评论数据出错!!!</p></div>';
                   }
                   replyContent.html(str1);
               });
           }
       }
    });
    eAnsSec.on('click', '.publish', function(){
        var that = this;
        var type = $(that).data('type');
        var elTextarea = $(that).prev('textarea');
        var eTip = elTextarea.prev('p.tip-msg');
        var eLi = $(that).parent().parent().parent().parent();
        var aid = eLi.data('aid');
        if(!elTextarea.val()){
            clearpop('请书写一定的内容');
            return ;
        }
        var content = marked(elTextarea.val());
        if(eTip.text()){
            console.log('change');
            content = '<p class="aiteAuthor">@ <a href="//doc.wooo.wang/u/'+eTip.data('uid')+'.html">'
            +eTip.find('span').text()+'</a>：</p>'+marked(elTextarea.val());
        }
        var para = {
            'tid' : tid,
            'html' : content
        };
        if(type == 1){
            para.fid = aid;
        }else if(type == 2){
            para.aid = aid;
        }else{
            clearpop('系统异常，请刷新后再试');
            return ;
        }
        // 是否传递被回复对象的ID
        $.post("/tie/ajaxpublish.html", para, function(res){
            var data = $.parseJSON(res);
            if(data.code == 200){
                if(type == 1){
                    var ansReplyEl = $('#ansReply'+aid);
                    var newReplyCount = parseInt(ansReplyEl.text())+1;
                    eLi.data('reply', newReplyCount);
                    ansReplyEl.text(newReplyCount);
                    $('#replyContent'+aid).append('<div class="wooo">'+content
                        +'</div><p class="faq-msg" data-aid="'+data.data+'"><a href="/u/'+uid+'.html" data-uid="'+uid+'">'+username
                        +'</a>&nbsp;&nbsp;'+getFormatTime(0,1)+'.&nbsp;&nbsp;<a href="javascript:void(0)" class="replyBtn">回复</a>'+
                        (manager ? '&nbsp;&nbsp;<a href="javascript:void(0)" class="delAnsBtn">删除</a>' : '')
                        +'</p>');
                    elTextarea.val('');
                    if(elTextarea.prev('p.tip-msg').text()){
                        elTextarea.prev('p.tip-msg').find('.closeUser').click();
                    }
                }else if(type == 2){
                    eLi.find('.wooo').append('<p class="faq-update-msg">'+getFormatTime(0,2)+' &nbsp;<strong>Update：</strong></p>'+content);
                    $('#replyBtn'+aid).click();
                }
            }
            clearpop(data.msg);
        });
    });
    eAnsSec.on('click', '.replyBtn', function(){
        var tmpTip = $(this).parent();
        var tmpUser = $(this).prev('a');
        var editDiv = tmpTip.parent().parent().find('.editDiv');
        editDiv.find('p.tip-msg').data('aid', tmpTip.data('aid')).data('uid', tmpUser.data('uid')).html('回复： <span>'+tmpUser.text()+'</span>&nbsp;&nbsp;<a href="javascript:void(0)" name="target" class="closeUser">[×]</a>');
       editDiv.find('a.publish').css('top',24);
       editDiv.find('textarea').focus();
    });
    eAnsSec.on('click', '.closeUser', function(){
       $(this).parent('p.tip-msg').next('textarea').next('a.publish').css('top',2);
       $(this).parent('p.tip-msg').html('');
    });
    eAnsSec.on('click', '.anspage a', function(){
        var that = this;
        var ansId = $(that).parent().data('aid');
        var pid = $(that).data('pid');
        $.get("/tie/ajaxgetreply/tid/"+tid+"/aid/"+ansId+'/p/'+pid, {}, function(res){
            var data = $.parseJSON(res);
            var str1 = '';
            var replyContent = $('#replyContent'+ansId);
            if(data.code == 200 && data.data.count > 0){
                for(var i in data.data.list){
                    var tmpData = data.data.list[i];
                    str1+='<div class="wooo">'+tmpData['html']+'</div><p class="faq-msg" data-aid="'+tmpData['id']+'">'+
                        '<a href="/u/'+tmpData['uid']+'.html" data-uid="'+
                        tmpData['uid']+'">'+tmpData['nick']+'</a>&nbsp;&nbsp;'+
                        getReplyTime(tmpData['create'])+'.&nbsp;&nbsp;'+
                        '<a href="javascript:void(0)" class="replyBtn">回复</a>';
                    str1 += manager ? '&nbsp;&nbsp;<a href="javascript:void(0)" class="delAnsBtn">删除</a>' : '';
                    str1 += '</p>';
                }
                $('#ansPage'+ansId).html(page(ansId, data.data.count, ansEvery, pid, ansNum));
            }else{
                str1 += '<div class="wooo"><p>获取评论数据出错!!!</p></div>';
            }
            replyContent.html(str1);
        });
    });
    /**
     * 获取指定时间戳的标准时间格式
     */
    function getFormatTime(){
        var time = arguments[0] ? arguments[0] : 0;
        var type = arguments[1] ? arguments[1] : 0;
        if(time){
            var now = new Date(time*1000);
        }else{
            var now = new Date();
        }
        if(type==0){
            return String(now.getFullYear()) + '-' + dealTime(now.getMonth() + 1) + '-' + dealTime(now.getDate());
        }else if(type == 1){
            return dealTime(now.getHours()) + ':' + dealTime(now.getMinutes()) + ':' + dealTime(now.getSeconds());
        }else{
            return String(now.getFullYear()) + '-' + dealTime(now.getMonth() + 1) + '-' + dealTime(now.getDate()) 
            + ' ' + dealTime(now.getHours()) + ':' + dealTime(now.getMinutes()) + ':' + dealTime(now.getSeconds());
        }
    }
    function dealTime(num) {
        return num < 10 ? '0' + String(num) : String(num);
    }
    function getReplyTime(num){
        var tmp = getFormatTime();
        if(tmp == getFormatTime(num)){
            return getFormatTime(num,1);
        }else{
            return getFormatTime(num);
        }
    }
    /* 分页功能 */
    function page(ansId, count, every, cur, num){
        var pages = Math.ceil(count / every);     // 总页面数
        if(pages <= 1){
            return '';
        }
        var first = '', last = '', start = '', end = '', mark = Math.ceil(num / 2);
        // FIRST 链接展示
        if(pages > num && cur > mark){
            first = '<a href="javascript:void(0)" data-pid="1">FIRST</a>';
        }
        // LAST 链接展示
        if(pages > num && cur < (pages - mark + 1)){
            last = '<a href="javascript:void(0)" data-pid="'+pages+'">LAST</a>';
        }
        // 中间的链接展示
        if(pages <= num){
            start = 1;
            end = pages;
        }else{
            if(cur < mark){
                start = 1;
            }else if(cur > (pages - mark)){
                start = pages - num + 1;
            }else{
                start = cur - mark + 1;
            }
            end = num;
        }
        var content = '';
        for(var i = 0; i < end; i++){
            if(start == 1){
                if(cur == 1){
                    content += '<a href="javascript:void(0)"  data-pid="1" class="current">1</a>';
                }else{
                    content += '<a href="javascript:void(0)" data-pid="1">1</a>';
                }
            }else{
                if(start == cur){
                    content += '<a href="javascript:void(0)" data-pid="'+start+'" class="current">'+start+'</a>';
                }else{
                    content += '<a href="javascript:void(0)" data-pid="'+start+'">'+start+'</a>';
                }
            }
            start ++;
        }
        return '<div class="anspage clearfix" data-aid="'+ansId +'">'+first+content+last+'</div>';
    }
    // 管理员对帖子的删除/加精/顶置功能
    var eDelete = $('#deleteTie'), eSetElite = $('#setElite'), eCancelElite = $('#cancelElite'), eSetTop = $('#setTop'), eCancelTop = $('#cancelTop');
    eDelete.on('click', function(){
        if(confirm('您是否确认删除该帖子！？')){
            $.post('/tie/deletetie.html', {tid: $(this).parent().data('tid')}, function(res){
                var data = $.parseJSON(res);
                if(data.code == 200){
                    clearpop('您已成功删除该帖子！', 800);
                    setTimeout(function(){
                        window.location.href = '/bbs/'+oid+'.html';
                    }, 800);
                }else{
                    clearpop(data.msg);
                }
            });
        }
    });
    eSetElite.on('click', function(){
        if(confirm('您是否确认设置该帖子为精华！？')){
            $.post('/tie/toggleElite.html', {tid: $(this).parent().data('tid'), type: 1}, function(res){
                var data = $.parseJSON(res);
                if(data.code == 200){
                    clearpop('您已成功设置该帖子为精华！', 800);
                    setTimeout(function(){
                        window.location.reload();
                    }, 800);
                }else{
                    clearpop('设置精华失败，请刷新后再试！');
                }
            });
        }
    });
    eCancelElite.on('click', function(){
        if(confirm('您是否确认取消该帖子精华！？')){
            $.post('/tie/toggleElite.html', {tid: $(this).parent().data('tid'), type: 0}, function(res){
                var data = $.parseJSON(res);
                if(data.code == 200){
                    clearpop('您已成功取消该帖子精华！', 800);
                    setTimeout(function(){
                        window.location.reload();
                    }, 800);
                }else{
                    clearpop('取消精华失败，请刷新后再试！');
                }
            });
        }
    });
    eSetTop.on('click', function(){
        if(confirm('您是否确认设置该帖子为顶置！？')){
            $.post('/tie/toggleTop.html', {tid: $(this).parent().data('tid'), type: 1}, function(res){
                var data = $.parseJSON(res);
                if(data.code == 200){
                    clearpop('您已成功设置该帖子为精华！', 800);
                    setTimeout(function(){
                        window.location.reload();
                    }, 800);
                }else{
                    clearpop('设置精华失败，请刷新后再试！');
                }
            });
        }
    });
    eCancelTop.on('click', function(){
        if(confirm('您是否确认取消该帖子顶置！？')){
            $.post('/tie/toggleTop.html', {tid: $(this).parent().data('tid'), type: 0}, function(res){
                var data = $.parseJSON(res);
                if(data.code == 200){
                    clearpop('您已成功取消该帖子顶置！', 800);
                    setTimeout(function(){
                        window.location.reload();
                    }, 800);
                }else{
                    clearpop('取消顶置失败，请刷新后再试！');
                }
            });
        }
    });
    eAnsSec.on('click', '.delAnsBtn', function(){
        var that = this;
        if(confirm('您是否确认删除该回复！？')){
            var aid = $(that).parent().data('aid');
            $.post('/tie/deleteans.html', {tid: tid, aid: aid}, function(res){
                var data = $.parseJSON(res);
                if(data.code == 200){
                    clearpop('您已成功删除该回复！');
                    var tmpObj = $('#ans'+aid);
                    if(tmpObj.length){
                        tmpObj.remove();
                    }else{
                        $(that).parent().prev('.wooo').remove();
                        $(that).parent().remove();
                    }
                }else{
                    clearpop(data.msg);
                }
            });
        }
    });


























});